<template>
  <div>
    <!--table 表头前面的按钮-->
    <div class="common-table-title-but" ref="tableTopBut">
      <template v-for="(item,key) in tableProp.topButOption">
        <el-button
            :key="key"
            :type="item.type"
            :icon="`${item.icon} el-icon--left`"
            v-if="Utils.arrayContain(item.routerRole,$store.state.routerRole)"
            @click="HandleUtils.handleParent($parent,item.methodName)"
        >
          {{ item.name }}
        </el-button>
      </template>
      <el-button
          icon="el-icon-setting el-icon--left"
          @click="HandleUtils.handleParent($parent,'tableSetUpSearchClick')"
          v-if="tableProp.tableToConfigure"
      >
        配置表头
      </el-button>
    </div>

    <!--table 配置-->
    <el-table
        ref="commonTable"
        :data="tableData"
        border
        style="width: 100%"
        :max-height="tableProp.tableHeight"
        @selection-change="handleSelectionChange"
        :summary-method="getSummaries"
        :show-summary="tableProp.showSummary"
        :header-cell-style="{background:'#f5f7fa',color:'#081333',fontWeight: 'normal'}"
        :default-expand-all="tableProp.defaultExpandAll"
        :row-key="tableProp.multipleSelectionId"
        :tree-props="{children: 'children', hasChildren: 'hasChildren'}"
        v-loading="tableProp.loading"
    >
      <template v-if="tableProp.tableExpandComponent?true:false">
        <el-table-column
            fixed="left"
            type="expand"
        >
          <template slot-scope="props">
            <!--:ref="item.ref"-->
            <component :is="tableProp.tableExpandComponent" :props="props"></component>
          </template>
        </el-table-column>
      </template>

      <!--序号-->
      <el-table-column label="序号" type="index" width="50" align="center" :fixed="tableProp.serialNoFixed" v-if="tableProp.serialNo"/>
      <!--全选按钮-->
      <el-table-column type="selection" width="50" align="center" :fixed="tableProp.multipleNoFixed" v-if="tableProp.multipleNo"></el-table-column>

      <template v-for="(item,key) in toConfigureFieldDialog.tableFieldProp">
        <template v-if=" item.statusRole?(item.statusRole.length?item.statusRole.includes(tabsProp.tabsActive):true):true">
          <el-table-column
              :key="key"
              :label="item.label"
              :fixed="item.fixed"
              :min-width="item.tableMinWidth?item.tableMinWidth:150"
              :show-overflow-tooltip="item.tableShowOverflowTooltip"
              :prop="item.field"
              v-if="Utils.arrayContain(item.routerRole,$store.state.routerRole)  && !item.tableShow"
          >
            <template slot-scope="scope">
              <template v-if="item.type==='输入框'">

                {{ scope.row[item.field] }}
              </template>
              <template v-if="item.type==='密码框'">
                ********
              </template>
              <template v-if="item.type==='文本域'">
                {{ scope.row[item.field] }}
              </template>
              <template v-if="item.type==='单选框'">
                <template v-for="item2 in item.option">
                  <template v-if="scope.row[item.field]===item2.value">
                    {{ item2.label }}
                  </template>
                </template>
              </template>
              <template v-if="item.type==='多选框'">
                <label v-for="(item2,key2) in scope.row[item.field]" :key="key2">
                  <label v-for="(item3,key3) in item.option" :key="key3">
                    <label v-if="item2=== item3.value">
                      {{ item3.label }}<i v-if="scope.row[item.field].length>key2+1">、</i>
                    </label>
                  </label>
                </label>
              </template>
              <template v-if="item.type==='下拉框'">
                <!--不是多选-->
                <template v-if="!item.multiple">
                  <!--不是分组-->
                  <template v-if="!item.group">
                    <template v-for="item2  in item.option">
                      <template v-if="scope.row[item.field]===item2.value">
                        {{ item2.label }}
                      </template>
                    </template>
                  </template>
                  <!--是分组-->
                  <template v-else>
                    <template v-for="item2 in item.option">
                      <template v-for="item3 in item2.children">
                        <template v-if="scope.row[item.field]===item3.value">
                          {{ item3.label }}
                        </template>
                      </template>
                    </template>
                  </template>
                </template>

                <!--是多选-->
                <template v-else>
                  <!--不是分组-->
                  <template v-if="!item.group">
                    <label v-for="(item2,key2) in scope.row[item.field]" :key="key2">
                      <label v-for="(item3,key3) in item.option" :key="key3">
                        <label v-if="item2=== item3.value">
                          {{ item3.label }}<i v-if="scope.row[item.field].length>key2+1">、</i>
                        </label>
                      </label>
                    </label>
                  </template>
                  <!--是分组-->
                  <template v-else>
                    <label v-for="(item2,key2) in scope.row[item.field]" :key="key2">
                      <label v-for="(item3,key3) in item.option" :key="key3">
                        <label v-for="(item4,key4) in item3.children" :key="key4">
                          <label v-if="item2=== item4.value">
                            {{ item4.label }}<i v-if="scope.row[item.field].length>key2+1">、</i>
                          </label>
                        </label>
                      </label>
                    </label>
                  </template>

                </template>

              </template>
              <template v-if="item.type==='级联选择器'">
                <!--没有多选-->
                <template v-if="!item.multiple">
                  <label v-for="(item2,key2) in scope.row[item.field]" :key="key2">
                    <label v-for="(item3,key3) in item.option" :key="key3">
                      <label v-if="item2=== item3.value">
                        {{ item3.label }}<i v-if="scope.row[item.field].length>key2+1">/</i>
                      </label>
                      <label v-for="(item4,key4) in item3.children" :key="key4">
                        <label v-if="item2=== item4.value">
                          {{ item4.label }}<i v-if="scope.row[item.field].length>key2+1">/</i>
                        </label>
                        <label v-for="(item5,key5) in item4.children" :key="key5">
                          <label v-if="item2=== item5.value">
                            {{ item5.label }}<i v-if="scope.row[item.field].length>key2+1">/</i>
                          </label>
                        </label>
                      </label>
                    </label>
                  </label>
                </template>
                <!--有多选-->
                <template v-else>
                  <div v-for="(item2,key2) in scope.row[item.field]" :key="key2">
                    <label v-for="(item3,key3) in item2" :key="key3">
                      <label v-for="(item4,key4) in item.option" :key="key4">
                        <label v-if="item3=== item4.value">
                          {{ item4.label }}<i v-if="item2.length>key3+1">/</i>
                        </label>
                        <label v-for="(item5,key5) in item4.children" :key="key5">
                          <label v-if="item3=== item5.value">
                            {{ item5.label }}<i v-if="item2.length>key3+1">/</i>
                          </label>
                          <label v-for="(item6,key6) in item5.children" :key="key6">
                            <label v-if="item3=== item6.value">
                              {{ item6.label }}<i v-if="item2.length>key3+1">/</i>
                            </label>
                          </label>
                        </label>
                      </label>
                    </label>
                  </div>
                </template>
              </template>
              <template v-if="item.type==='日期选择器'">
                <!--年-->
                <template v-if="item.timeType==='year'">
                  {{ scope.row[item.field] ? Utils.timeDate(scope.row[item.field], 1) : '' }}
                </template>
                <!--月-->
                <template v-if="item.timeType==='month'">
                  {{ scope.row[item.field] ? Utils.timeDate(scope.row[item.field], 2) : '' }}
                </template>
                <!--日-->
                <template v-if="item.timeType==='date'">
                  {{ scope.row[item.field] ? Utils.timeDate(scope.row[item.field], 3) : '' }}
                </template>
                <!--日期和时间-->
                <template v-if="item.timeType==='datetime'">
                  {{ scope.row[item.field] ? Utils.timeDate(scope.row[item.field], 4) : '' }}
                </template>
                <!--多个日-->
                <template v-if="item.timeType==='dates'">
                  <div v-for="(item2,key2) in scope.row[item.field]" :key="key2">
                    {{ item2 ? Utils.timeDate(item2, 3) : '' }}
                  </div>
                </template>
                <!--日期和时间范围-->
                <template v-if="item.timeType==='datetimerange'">
                  <div v-for="(item2,key2) in scope.row[item.field]" :key="key2">
                    {{ item2 ? Utils.timeDate(item2, 4) : '' }}
                    <div v-if="scope.row[item.field].length>key2+1" style="text-align: center">至</div>
                  </div>
                  <div>相差：{{ scope.row[item.field].length === 2 ? Utils.intervalTime(scope.row[item.field], 4) : 0 }}
                  </div>
                </template>
                <!--日期范围-->
                <template v-if="item.timeType==='daterange'">
                  <div v-for="(item2,key2) in scope.row[item.field]" :key="key2">
                    {{ item2 ? Utils.timeDate(item2, 3) : '' }}
                    <div v-if="scope.row[item.field].length>key2+1">至</div>
                  </div>
                  <div>相差：{{ scope.row[item.field].length === 2 ? Utils.intervalTime(scope.row[item.field], 1) : 0 }}
                  </div>
                </template>
                <!--月份范围-->
                <template v-if="item.timeType==='monthrange'">
                  <div v-for="(item2,key2) in scope.row[item.field]" :key="key2">
                    {{ item2 ? Utils.timeDate(item2) : '' }}
                    <div v-if="scope.row[item.field].length>key2+1">至</div>
                  </div>
                  <div>相差：{{ scope.row[item.field].length === 2 ? Utils.intervalTime(scope.row[item.field], 5) : 0 }}
                  </div>
                </template>
              </template>
              <template v-if="item.type==='文件上传'">
                <div class="table-upload-file-box">
                  <ul>
                    <li
                        v-for="(item2,key2) in scope.row[item.field]"
                        :key="key2"
                        @click="uploadFileDownload(item2[item.urlType],item2)"
                    >
                      <i class="el-icon-notebook-2"></i>
                      <span>{{ item2.name }}</span>
                      <i class="el-icon-download"></i>
                    </li>
                  </ul>
                </div>
              </template>
              <template v-if="item.type==='图片上传'">
                <div class="table-upload-img-show">
                  <ul>
                    <li v-for="(item2,key2) in  scope.row[item.field]" :key="key2">
                      <el-image
                          :src="item2[item.urlType]"
                          :preview-src-list="Utils.arrayMoveOne(item2[item.urlType],scope.row[item.field],item.urlType)"
                          @click="clickImage"
                      >
                      </el-image>
                    </li>
                  </ul>
                </div>
              </template>
            </template>
          </el-table-column>
        </template>
      </template>
      <!--操作按钮-->
      <el-table-column
          label="操作"
          :fixed="tableProp.tableButOptionNoFixed"
          :width="tableProp.tableButOptionWidth"
          v-if="tableProp.tableButOptionShow"
          align="center"
      >
        <template slot-scope="scope">
          <template v-for="(item2,key2) in tableProp.tableButOption">
            <label v-if="Utils.arrayContain(item2.routerRole,$store.state.routerRole)" :key="key2"
                   class="table-operation-but">
              <template v-if="item2.statusArray.length>0">
                <el-button
                    :type="item2.type"
                    :icon="`${item2.icon} el-icon--left`"
                    @click="HandleUtils.handleParent($parent,item2.methodName,scope.row,scope.$index)"
                    v-if="item2.statusArray.includes(scope.row[tableProp.tableButStatusField])"
                >
                  {{ item2.name }}
                </el-button>
              </template>
              <template v-else>
                <el-button
                    :type="item2.type"
                    :icon="`${item2.icon} el-icon--left`"
                    @click="HandleUtils.handleParent($parent,item2.methodName,scope.row,scope.$index)"
                >
                  {{ item2.name }}
                </el-button>
              </template>
            </label>
          </template>
        </template>
      </el-table-column>
    </el-table>

    <!--分页-->
    <div class="common-pagination">
      <el-pagination
          @size-change="pageSizeChange"
          @current-change="pageCurrentChange"
          :current-page="paginationProp.currentPage"
          :page-sizes="[10, 20, 50, 100,500,1000]"
          :page-size="paginationProp.pageSize"
          layout="total,sizes, prev, pager, next, jumper"
          :total="paginationProp.total"
      />
    </div>
  </div>
</template>

<script>

export default {
  components: {},
  props: ['tableProp', 'tableData', 'toConfigureFieldDialog', 'paginationProp', 'tabsProp'],
  data() {
    return {
      multipleSelection: [],
      wrapperElem: null,//图片放大
    };
  },
  mounted() {

  },
  methods: {
    // 自定义的合计计算方法
    getSummaries() {
      // const { columns, data } = param; //columns显示了那些字段  data有几条数据
      let skip = 1;
      if (this.tableProp.serialNo && this.tableProp.multipleNo) {
        skip = 2;

      }
      const sums = [];
      if (skip === 1) {
        sums.push(this.tableProp.showSummaryTitle);
      } else {
        sums.push(this.tableProp.showSummaryTitle);
        sums.push('');
      }
      if (!this.tableProp.serialNo && !this.tableProp.multipleNo) {
        skip = 0
      }
      for (let i = 0; i < this.toConfigureFieldDialog.tableFieldProp.length; i++) {
        if (this.toConfigureFieldDialog.tableFieldProp[i].totalOrNot) {
          let total = 0;
          for (let j = 0; j < this.tableData.length; j++) {
            if (!isNaN(Number(this.tableData[j][this.toConfigureFieldDialog.tableFieldProp[i].field]))) {//是否是数字
              total = total + Number(this.tableData[j][this.toConfigureFieldDialog.tableFieldProp[i].field]);
            }
          }
          if (this.toConfigureFieldDialog.tableFieldProp[i].totalCompany) {
            sums[i + skip] = `${total}  ${this.toConfigureFieldDialog.tableFieldProp[i].totalCompany}`;
          } else {
            sums[i + skip] = total;
          }

        } else {
          if (i != 0) {
            sums[i + skip] = '';
          }
        }
      }
      return sums;
    },
    //有多选 多选后的值
    handleSelectionChange(val) {
      let multipleSelection = [];
      for (let i = 0; i < val.length; i++) {
        if (val[i][this.tableProp.multipleSelectionId]) {
          multipleSelection.push(val[i][this.tableProp.multipleSelectionId])
        }
      }
      this.tableProp.multipleSelection = multipleSelection;
    },
    //图片放大下载 开始
    clickImage() {
      this.$nextTick(() => {
        let wrapper = document.getElementsByClassName(
            'el-image-viewer__actions__inner'
        )
        let downImg = document.createElement('i')
        downImg.setAttribute('class', 'el-icon-download')
        wrapper[0].appendChild(downImg)
        if (wrapper.length > 0) {
          this.wrapperElem = wrapper[0]
          this.cusClickHandler()
        }
      })
    },
    cusClickHandler() {
      this.wrapperElem.addEventListener('click', this.hideCusBtn)
    },
    hideCusBtn(e) {
      let className = e.target.className
      if (className === 'el-icon-download') {
        let imgUrl = document.getElementsByClassName(
            'el-image-viewer__canvas'
        )[0].children[0].src
        this.downloadImage(imgUrl)
      }
    },
    downloadImage(imgUrl) {
      let tmpArr = imgUrl.split('/')
      let fileName = tmpArr[tmpArr.length - 1]
      window.URL = window.URL || window.webkitURL
      let xhr = new XMLHttpRequest()
      xhr.open('get', imgUrl, true)
      xhr.responseType = 'blob'
      xhr.onload = function () {
        if (this.status == 200) {
          //得到一个blob对象
          let blob = this.response
          let fileUrl = window.URL.createObjectURL(blob)
          let a = document.createElement('a')
          ;(document.body || document.documentElement).appendChild(a)
          a.href = fileUrl
          if ('download' in a) {
            a.download = fileName
          } else {
            a.setAttribute('download', fileName)
          }
          a.target = '_self'
          a.click()
          a.remove()
        }
      }
      xhr.send()
    },
    //图片放大下载结束

    //附件下载
    uploadFileDownload(url, item) {
      //下载不了是跨域的问题
      // const URL = this.$store.state.env + '/' + url
      const URL =  url
      // let tmpArr = URL.split('/')
      // let fileName = tmpArr[tmpArr.length - 1]
      window.URL = window.URL || window.webkitURL
      let xhr = new XMLHttpRequest()
      xhr.open('get', URL, true)
      xhr.responseType = 'blob'
      xhr.onload = function () {
        if (this.status == 200) {
          //得到一个blob对象
          let blob = this.response
          let fileUrl = window.URL.createObjectURL(blob)
          let a = document.createElement('a')
          ;(document.body || document.documentElement).appendChild(a)
          a.href = fileUrl
          if ('download' in a) {
            a.download = item.name
          } else {
            a.setAttribute('download', item.name)
          }
          a.target = '_self'
          a.click()
          a.remove()
        }
      }
      xhr.send()
      // window.open(url)
    },
    //分页 选择了每页几条
    pageSizeChange(val) {
      this.HandleUtils.handleParent(this.$parent, 'pageSizeChange', val)
    },
    //分页 点击了跳转到第几页
    pageCurrentChange(val) {
      this.HandleUtils.handleParent(this.$parent, 'pageCurrentChange', val)
    },
  },
};
</script>

<style lang="scss">
.table-upload-file-box {
  ul {
    li {
      margin: 3px 0;
      border-radius: 5px;
      font-size: 14px;
      @include flex();
      cursor: pointer;

      span {
        font-size: 12px;
        margin-right: 8px;
      }

      i {
        font-size: 13px;
        background: #303133;
        border-radius: 50%;
        //padding: 3px;
        margin-right: 5px;
        color: #fff;

        &:nth-of-type(1) {
          background: none;
          font-size: 18px;
          color: $color-basic;
        }

        &:nth-of-type(2) {
          background: $color-success;
        }
      }
    }
  }
}

.table-upload-img-show {
  ul {
    @include flex(wrap);

    li {
      @include flex();
      margin: 5px;

      img {
        width: 80px !important;
        height: 80px !important;
        border-radius: 8px;
      }
    }
  }

}

.table-operation-but {
  .el-button + .el-button {
    margin: 0px;
  }

  .el-button {
    margin: 5px;
  }

}
</style>
